using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;

//namespace ibba.src.sl.recursos.Codes.Extensions
//{
    public static class ListExtensions
    {
        public static List<T> OrderByList<T>(this List<T> pList, String pPropertyName, Boolean pAscendente)
        {
            pList.Sort(new OrderByList<T>(pPropertyName, pAscendente));
            return pList;
        }

        public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> collection)
        {
            var oc = new ObservableCollection<T>();
            AddRange(oc, collection);
            
            return oc;
        }

        public static void AddRange<T>(this ObservableCollection<T> oc, IEnumerable<T> collection)
        {
            if (collection == null)
                throw new ArgumentNullException("collection");

            foreach (var item in collection)
                oc.Add(item);

        }

        /// <summary>
        /// Alterar propriedades de uma lista de objetos retornado via LINQ Query
        /// </summary>
        /// <typeparam name="TSource">Tipo Generico</typeparam>
        /// <param name="input">Lista a ser alterada</param>
        /// <param name="change">Propriedades alteradas</param>
        /// <returns>Lista alterada</returns>
        /// <example>
        /// var ret = (from x in lista
        ///            select x.Modify(x1 =>
        ///            {
        ///                 x.Valor = x.Valor / 100;
        ///                 x.ValDecimal = x.Valor / 100;
        ///            });
        /// </example>
        public static TSource Modify<TSource>(this TSource input, Action<TSource> change)
        {
            change(input);
            return input;
        }
    }

    class OrderByList<T> : IComparer<T>
    {
        string _propertyName;
        bool _ascendente;

        public OrderByList(String pPropertyName, Boolean pAscendente)
        {
            this._propertyName = pPropertyName;
            this._ascendente = pAscendente;
        }

        public int Compare(T x, T y)
        {
            PropertyInfo propriedade = typeof(T).GetProperty(this._propertyName);

            IComparable objX = (IComparable)propriedade.GetValue(x, null);
            IComparable objY = (IComparable)propriedade.GetValue(y, null);

            if (this._ascendente)
                return (objX.CompareTo(objY));
            else
                return (objY.CompareTo(objX));
        }
    }

//}